/*****************************************************************************
 *  ENTROPY - emerging network to reduce orwellian potency yield
 *
 *  Copyright (C) 2002 Juergen Buchmueller <pullmoll@stop1984.com>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software Foundation,
 *  Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 *	$Id: logger.c,v 1.2 2005/07/12 23:12:29 pullmoll Exp $
 *****************************************************************************/
#include "osd.h"
#include "config.h"
#include "tools.h"
#include "logger.h"

#if	DEBUG

int logprintf(int lvl, const char *func, const char *file, int line, char *msg)
{
	pid_t pid = getpid();
	char tmstr[32];
	struct timeval tv;
	struct tm tm;
	FILE *fp = NULL;
	struct flock fl;
	size_t length = 0;
	int e = errno;

	if (NULL == g_conf) {
		errno = e;
		return -1;
	}

	gettimeofday(&tv, NULL);
	memcpy(&tm, gmtime((const time_t *)&tv.tv_sec), sizeof(tm));
	pm_snprintf(tmstr, sizeof(tmstr), "%02u:%02u:%02u.%03u",
		tm.tm_hour, tm.tm_min, tm.tm_sec, (unsigned)(tv.tv_usec / 1000));

	fp = fopen(LOGFILE, "a");
	if (NULL == fp) {
		errno = e;
		return -1;
	}
	/* flock end of file */
	memset(&fl, 0, sizeof(fl));
	fl.l_start = 0;
	fl.l_len = 1;
	fl.l_type = F_WRLCK;
	fl.l_whence = SEEK_END;
	if (0 != fcntl(fileno(fp), F_SETLKW, &fl)) {
		errno = e;
		return -1;
	}
	length = fprintf(fp, "%s:%d:{%d}:%s(%s:%d): %s",
		tmstr, lvl, (int)pid, func, file, line, msg);
	free(msg);
	fl.l_type = F_UNLCK;
	if (0 != fcntl(fileno(fp), F_SETLKW, &fl)) {
		fclose(fp);
		errno = e;
		return -1;
	}
	fclose(fp);

	errno = e;
	return length;
}

char *logappend(const char *fmt, ...)
{
	char *buff;
	size_t size;
	va_list ap;

	va_start(ap, fmt);
	size = pm_vsnprintf(NULL, 0, fmt, ap);
	buff = malloc(size + 1);
	if (NULL == buff) {
		va_end(ap);
		return strdup("[out of memory]");
	}
	pm_vsnprintf(buff, size + 1, fmt, ap);
	va_end(ap);

	return buff;
}

#endif	/* DEBUG */
